﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace CourierManager
{
    public abstract class Employee : Subject, IPerson
    {
        private string path = "../../../CourierManager/Employees.txt";
        protected bool IsANewEmployee { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public decimal Salary { get; set; }
        public int EmployeeNumber { get; set; }
        private List<string> EmployeesList { get; set; }

        public string PathToDataBase 
        {
            get { return this.path; }
            set { this.path = value; }
        }

        public Employee(string firstName, string lastName, string address, ulong idNumber, ulong phone,decimal salary)
            : base(address, idNumber, phone)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
            this.IsANewEmployee = true;
            this.Salary = salary;
        }

        public List<string> ReadEmployeeData()
        {
            StreamReader reader = new StreamReader(path);
            List<string> employees = new List<string>();
            int lineCounter = 1;
            using (reader)
            {
                string line = reader.ReadLine();

                while (line != null && String.IsNullOrWhiteSpace(line) == false)
                {
                    string[] splittedLine = line.Split('*');

                    if (splittedLine[4] == this.IDNumber.ToString())
                    {
                        this.IsANewEmployee = false;
                        this.EmployeeNumber = lineCounter;
                    }
                    employees.Add(line);
                    line = reader.ReadLine();
                    lineCounter++;
                }
            }
            return employees;
        }

        public virtual void SaveEmployeeData()
        {
            if (this.FirstName != null)
            {
                this.EmployeesList = this.ReadEmployeeData();
                if (this.IsANewEmployee == true)
                {
                    StreamWriter writer = new StreamWriter(this.path, true);
                    //string type = Convert.ToString(this);
                    using (writer)
                    {
                        Type classType = this.GetType();
                        string employee = String.Format("{0}*{1}*{2}*{3}*{4}*{5}*{6}", classType.Name, this.FirstName, this.LastName,
                            this.Address, this.IDNumber, this.Phone, this.Salary);
                        writer.WriteLine(employee);
                    }
                    this.EmployeeNumber = EmployeesList.Count;
                }
            }
            
        }
    }
}
